﻿#if UNITY_EDITOR
using System.IO;
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine;
using UnityEngine.U2D;
/// <summary>
/// 生成图集文件夹
/// </summary>
public class ESF_BuildSpriteAtlasFolder
{
    /// <summary>
    /// 读取Sprite的根文件夹
    /// </summary>
    public string readSpritesRoot { get; private set; }

    /// <summary>
    /// 写入SpriteAtlas文件的根文件夹
    /// </summary>
    public string writeSpriteAtlasRoot { get; private set; }

    /// <summary>
    /// 要生成SpriteAtlas的图片源文件夹
    /// </summary>
    public string buildSpriteAtlasSrcFolder { get; private set; }

    /// <summary>
    /// enESF_SpriteAtlas枚举名称
    /// </summary>
    public string enESF_SpriteAtlasName { get; private set; }

    /// <summary>
    /// 语言包
    /// </summary>
    public enESF_AllLanguageClassify language { get; private set; }

    /// <summary>
    /// enESF_LanguageRootFolder枚举名称
    /// </summary>
    public string enESF_LanguageRootFolderName { get; private set; }

    /// <summary>
    /// 保存SpriteAtlas文件路径
    /// </summary>
    public string saveSpriteAtlasPath { get; private set; }

    /// <summary>
    /// 相对于保存SpriteAtlas文件路径的语言包格式串
    /// </summary>
    public string relativeSavePathLanFormat { get; private set; }

    /// <summary>
    /// 图集名称
    /// </summary>
    public string spriteAtlasName { get; private set; }

    /// <summary>
    /// 图集名称【不带后缀名】
    /// </summary>
    public string spriteAtlasNameWithoutExtension { get; private set; }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="_readSpritesRoot">读取Sprite的根文件夹</param>
    /// <param name="_writeSpriteAtlasRoot">写入SpriteAtlas文件的根文件夹</param>
    public ESF_BuildSpriteAtlasFolder(string _readSpritesRoot, string _writeSpriteAtlasRoot, string _buildSpriteAtlasSrcFolder)
    {
        readSpritesRoot = _readSpritesRoot.ESF_TransPathSeparatorCharToUnityChar();
        writeSpriteAtlasRoot = _writeSpriteAtlasRoot.ESF_TransPathSeparatorCharToUnityChar();
        buildSpriteAtlasSrcFolder = _buildSpriteAtlasSrcFolder.ESF_TransPathSeparatorCharToUnityChar();
        OnResolver();
    }

    /// <summary>
    /// 解析
    /// </summary>
    void OnResolver()
    {
        enESF_AllLanguageClassify lan = 0;
        string rf = string.Empty;
        string sub = ESF_Logic.assetBundleBuild.xml.GetRelativeLangPath(buildSpriteAtlasSrcFolder, ref lan, ref rf);
        language = lan;
        enESF_LanguageRootFolderName = rf.ESF_OnlyCNUAndOtherReplaceU().ToUpper();
        enESF_SpriteAtlasName = Path.Combine(rf, sub).ESF_OnlyCNUAndOtherReplaceU().ToUpper();

        string relativePath = buildSpriteAtlasSrcFolder.Replace(readSpritesRoot, "").ESF_ForceRelativePath();
        spriteAtlasNameWithoutExtension = $"{enESF_SpriteAtlasName}_{lan}";
        spriteAtlasName = spriteAtlasNameWithoutExtension + enESF_UnityFileExt.SpriteAtlas.ESF_FirstAttribute<ESF_FileExtAttribute>().ext;
        saveSpriteAtlasPath = Path.Combine(Path.Combine(writeSpriteAtlasRoot, relativePath), spriteAtlasName).ESF_TransPathSeparatorCharToUnityChar();

        string lanFormatName = $"{enESF_SpriteAtlasName}_{{0}}" + enESF_UnityFileExt.SpriteAtlas.ESF_FirstAttribute<ESF_FileExtAttribute>().ext;
        relativeSavePathLanFormat = Path.Combine(Path.GetDirectoryName(ESF_Utility.GetSubTo(saveSpriteAtlasPath, writeSpriteAtlasRoot)), lanFormatName).ESF_TransPathSeparatorCharToUnityChar();        
    }

    /// <summary>
    /// 检测SpriteAtlas
    /// </summary>
    /// <returns>SpriteAtlas</returns>
    public SpriteAtlas CheckSpriteAtlas()
    {
        SpriteAtlas sa = null;
        if (File.Exists(saveSpriteAtlasPath))
        {
            sa = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(saveSpriteAtlasPath);
            Object[] objs = sa.GetPackables();
            bool isChange = false;
            if (objs != null && objs.Length > 0)
            {
                string path = AssetDatabase.GetAssetPath(objs[0]);
                isChange = !path.Equals(buildSpriteAtlasSrcFolder);
            }
            else
            {
                isChange = true;
            }
            if (isChange)
            {
                sa.Remove(objs);
                sa.Add(new Object[] { AssetDatabase.LoadMainAssetAtPath(buildSpriteAtlasSrcFolder) });
            }
        }
        else
        {
            sa = new SpriteAtlas();
            FileInfo assest = new FileInfo(saveSpriteAtlasPath);
            if (!assest.Directory.Exists)
            {
                Directory.CreateDirectory(assest.Directory.FullName);
            }
            sa.Add(new Object[] { AssetDatabase.LoadMainAssetAtPath(buildSpriteAtlasSrcFolder) });
            AssetDatabase.CreateAsset(sa, saveSpriteAtlasPath);            
        }
        SpriteAtlasPackingSettings settings = sa.GetPackingSettings();
        sa.SetIncludeInBuild(false);
        settings.enableRotation = false;
        settings.enableTightPacking = false;
        sa.SetPackingSettings(settings);        
        return sa;
    }
}
#endif
